"""
轮播图相关视图
"""

from rest_framework import viewsets, filters, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view

from pecco_site.models import CarouselItem
from ..serializers.carousel import CarouselListSerializer, CarouselDetailSerializer
from ..filters import CarouselFilter
from ..permissions import IsAdminUser


@extend_schema_view(
    list=extend_schema(summary='获取轮播图列表', tags=['轮播图管理']),
    retrieve=extend_schema(summary='获取轮播图详情', tags=['轮播图管理']),
    create=extend_schema(summary='创建轮播图', tags=['轮播图管理']),
    update=extend_schema(summary='更新轮播图', tags=['轮播图管理']),
    partial_update=extend_schema(summary='部分更新轮播图', tags=['轮播图管理']),
    destroy=extend_schema(summary='删除轮播图', tags=['轮播图管理']),
)
class CarouselViewSet(viewsets.ModelViewSet):
    """轮播图管理 ViewSet"""
    queryset = CarouselItem.objects.all().prefetch_related('translations')
    permission_classes = [IsAuthenticated, IsAdminUser]
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = CarouselFilter
    ordering_fields = ['sort_order', 'created_at', 'updated_at']
    ordering = ['sort_order']

    def get_serializer_class(self):
        if self.action == 'list':
            return CarouselListSerializer
        return CarouselDetailSerializer

    @extend_schema(summary='切换轮播图激活状态', tags=['轮播图管理'])
    @action(detail=True, methods=['patch'])
    def toggle_active(self, request, pk=None):
        """切换轮播图激活状态"""
        carousel = self.get_object()
        carousel.is_active = not carousel.is_active
        carousel.save()
        return Response({'is_active': carousel.is_active})

